<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="top">
      <CommonContainer title="基础信息">
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="模版名称" prop="templateName">
              <el-input v-model.trim="form.templateName" placeholder="请输入模版名称" maxlength="30"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="模版类型" prop="templateClassification">
              <el-select v-model="form.templateClassification" placeholder="请选择模版类型" style="width: 100%" @change="getContractTemplateParams">
                <el-option v-for="dict in dict.type.other_contract_template_type" :label="dict.label" :value="parseInt(dict.value)" :key="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="是否客户模版:" prop="isCustomerTemplate" required>
              <el-radio-group v-model="form.isCustomerTemplate">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="2">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <template v-if="form.isCustomerTemplate==1">
            <el-col :span="8">
              <el-form-item label="关联客户" prop="customerNames">
                <div @click="chooseCustomer">
                  <el-input v-model="form.customerNames" placeholder="请选择客户" readonly></el-input>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="开始生效额度申请" prop="applicationNo">
                <div @click="chooseQuotaApplication">
                  <el-input v-model="form.applicationNo" placeholder="请选择额度申请" readonly></el-input>
                </div>
              </el-form-item>
            </el-col>
          </template>

          <el-col :span="24">
            <el-form-item label="说明">
              <el-input type="textarea" placeholder="请输入说明" v-model="form.templateRemark" maxlength="500" :rows="5" show-word-limit></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="附件">
              <div class="flex">
                <image-common :up-type="2" info="上传附件" is-show-tip :file-type="fileType" :limit="20" :fileSize="50" v-model="form.templateAnnex"></image-common>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </CommonContainer>


      <CommonContainer title="合同模版">
        <div style="margin-top: 10px">
          <div class="flex-row-center">
            <el-button type="primary" @click="handleUploadFile">上传附件</el-button>
          </div>
          <div v-if="form.contractAnnex" style="margin-top: 15px">
            <image-common v-model="form.contractAnnex" :up-type="1" :limit="1"></image-common>
          </div>
          <div style="margin: 15px 0">
            <tinymce-editor v-model="form.contractContent" :tag-list="tagList"></tinymce-editor>
          </div>
        </div>
      </CommonContainer>

      <div class="card-wrap flex justify-end card-padding">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" v-loading="saveLoading" @click="submitForm">保存</el-button>
        <el-button type="primary" v-loading="submitLoading" @click="commitApproval"  v-if="form.approvalStatus==0">提交审批</el-button>
      </div>
    </el-form>
    <AssociatedCustomers v-if="form.isCustomerTemplate==1" ref="associatedCustomers" @success="selectCustomerSuccess"></AssociatedCustomers>
    <el-dialog
        title="附件是否导入合同模板"
        :visible.sync="uploadFileDialogVisible"
        width="30%"
        center>
      <span>注：请上传大小不超过50MB 格式为doc、docx格式的文件</span>
      <span slot="footer" class="flex-row-center-ar">
<!--             <contract-template-upload :upload-type="2" @uploadSuccess="unImportToEditor"></contract-template-upload>-->
        <el-button style="width: 100px; height: 40px; position: relative;" @click="uploadFileDialogVisible=false">取消</el-button>
        <contract-template-upload :upload-type="1" @uploadSuccess="importToEditor"></contract-template-upload>
      </span>
    </el-dialog>

    <select-quota-application ref="selectQuotaApplication" @success="selectQuotaApplicationCallBack"></select-quota-application>
  </div>
</template>

<script>
import SelectCompanyTemplate from "@/views/contractTemplate/components/SelectCompanyTemplate.vue";
import InputNumberRange from "@/components/InputNumberRange/index.vue";
import CustomTag from '../components/customTag.vue';
import ContractTemplateEditor from "@/components/Editor/contractTemplateEditor.vue";
import ContractTemplateUpload from "@/components/FileUpload/contractTemplateUpload.vue";
import TinymceEditor from "@/components/TinymceEditor/index.vue";
import * as contractTemplateApi from "@/api/contractTemplate/otherContractTemplate";
import SelectQuotaApplication from "@/views/contractTemplate/components/SelectQuotaApplication.vue";
import AssociatedCustomers from "@/views/contractTemplate/otherTemplate/components/AssociatedCustomers.vue";
import {contractTemplateParam} from "@/api/contractTemplate/contractTemplate"

export default {
  name: 'OtherTemplateAdd',
  dicts: ['other_contract_template_type'],
  components: {
    AssociatedCustomers,
    SelectQuotaApplication,
    SelectCompanyTemplate,
    InputNumberRange,
    CustomTag,
    ContractTemplateEditor,
    ContractTemplateUpload,
    TinymceEditor
  },
  data() {
    return {
      uploadFileDialogVisible: false,
      saveLoading: false,
      submitLoading: false,
      fileType: ['png', 'jpg', 'jpeg', 'pdf', 'excel', 'doc', 'docx', 'msg'],
      form: {
        templateName: null,
        templateClassification: null,
        isCustomerTemplate: 2,
        relatedCustomers: null,
        customerNames: null,
        customersIds: null,
        applicationNo: null,
        templateRemark: null,
        templateAnnex: null,//模版附件
        contractParam: null,
        contractAnnex: null,//合同附件
        contractContent: null,
      },
      rules: {
        templateName: [
          {required: true, message: '请输入模版名称', trigger: 'blur'},
        ],
        templateClassification: [
          {required: true, message: '请选择模版类型', trigger: 'blur'},
        ],
        customerNames: [
          {required: true, message: '请选择客户', trigger: 'change'},
        ],
      },

      tagList: []
    }
  },
  computed: {},
  methods: {
    unImportToEditor(data) {
      this.uploadFileDialogVisible = false
      this.form.contractAnnex = data?.ossId
    },
    importToEditor(data) {
      this.uploadFileDialogVisible = false
      this.form.contractContent = data?.richText
      this.form.contractAnnex = data?.ossId
    },
    //获取合同模版参数
    getContractTemplateParams(val) {
      let type = val + 1
      contractTemplateParam({
        type: type
      }).then(res => {
        this.tagList = res.data || [];
      })
    },
    //合同详情
    getContractTemplateDetail() {
      contractTemplateApi.contractTemplateDetails(this.$route.query.id).then(res => {
        this.form = res.data;
        if(this.form.templateClassification){
          this.getContractTemplateParams(this.form.templateClassification);
        }
        console.log('回显数据---', this.form)
      })
    },
    //关联客户
    chooseCustomer() {
      this.$refs.associatedCustomers.show()
    },
    //关联客户回调
    selectCustomerSuccess(customer) {
      this.form.relatedCustomers = customer.customerId;
      this.form.customerNames = customer.customerName;
      this.form.applicationNo = null;
    },
    // 选择额度申请
    chooseQuotaApplication() {
      if (!this.isNull(this.form.relatedCustomers)) {
        this.$refs.selectQuotaApplication.show(this.form.relatedCustomers)
      } else {
        this.$message.error('请先选择关联客户')
      }

    },
    //额度申请回调
    selectQuotaApplicationCallBack(quotaInfo) {
      this.form.applicationNo = quotaInfo.calcSchemeCode;
    },

    //合同模版附件上传成功的回调事件
    uploadSuccess(res) {
      this.form.contractContent = res.data;
    },
    // 选择参数
    handleCustomTag() {
      this.$refs.customtag.show();
    },
    handleUploadFile() {
      this.uploadFileDialogVisible = true
    },
    //取消
    cancel() {
      this.$confirm('确认取消吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.back()
      })

    },
    // 保存
    submitForm(type) {
      this.saveLoading = true
      if (this.$route.query.id) {//编辑
        contractTemplateApi.contractTemplateUpdate(this.form).then(res => {
          this.$message.success('保存成功')
          this.back()
        }).finally((f) => {
          this.saveLoading = false
        })
      } else {//新增
        contractTemplateApi.contractTemplateAdd(this.form).then(res => {
          this.$message.success('保存成功')
          this.back()
        }).finally((f) => {
          this.saveLoading = false
        })
      }

    },
    //提交审批
    commitApproval() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.submitForApproval()
        }
      })
    },
    submitForApproval() {
      this.submitLoading = true
      contractTemplateApi.submitForApproval(this.form).then(res => {
        this.$message.success('提交审批成功')
        this.back()
      }).finally((f) => {
        this.submitLoading = false
      })
    },
    back() {
      this.$router.back()
      this.$store.dispatch('tagsView/delView', this.$route)
    }

  },
  mounted() {
    const query = this.$route.query;
    if (query) {
      if (query.id) {
        this.$nextTick(() => {
          this.getContractTemplateDetail()
        })
      }
    }

  },

}
</script>

<style lang="scss" scoped>

::v-deep .el-form--label-top .el-form-item__label {
  padding: 0;
}

.el-form-item {
  margin-bottom: 15px;
  width: 70%;
}

::v-deep .el-form-item--small .el-form-item__content:has(.el-radio-group, .el-date-editor, .el-input, .el-checkbox) {
  line-height: 32px;
  height: 32px;
}


</style>
